package com.shiro;

import com.common.ShiroExceptionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.Factory;

/**
 * Shiro demo可单独使用
 */
public class ShiroTest {

    public static void main(String[] args) {
        //1、获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
        Factory<SecurityManager> factory =
                new IniSecurityManagerFactory("classpath:shiro.ini");
        //2、得到SecurityManager实例 并绑定给SecurityUtils
        SecurityManager securityManager = factory.getInstance();
        //进行绑定，如果少了这一句会出错 No SecurityManager accessible to the calling code
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken("zhang","456");
        try {
            subject.login(token);
        }catch (Exception e){
            ShiroExceptionUtil.getShiroExceptionUtil().savereason(e);
        }

        //断言用户已登录(断言,类似于测试的)
        Assert.isTrue(subject.isAuthenticated());

        Session session=subject.getSession();
        session.setAttribute("user","zhang");

        //断言用于测试
        Assert.hasText((String)session.getAttribute("user"));

        subject.logout();
    }
}
